package com.dannypatterson.as3p2p {
	
	import com.dannypatterson.as3p2p.events.OutgoingConnectionEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	
	/**
	 * This class is used to send out a request to another peer and listen for
	 * that peer to accept.
	 * 
	 * @author Danny Patterson
	 * 
	 * @todo add timeout if we can't connect to the stream, or if the user doesn't accept our connection
	 * @todo add onConnectionRefused callback
	 */
	public class OutgoingConnector extends EventDispatcher {
		
		private var stratusConnection:NetConnection;
		private var requestStream:NetStream;
		private var peer:Peer;
		
		/**
		 * @return (String) The peer's stratus id.
		 */
		public function get peerId():String {
			return peer.id;
		}
		
		/**
		 * @param stratusConnection (NetConnection) The stratus connection from teh connection manager.
		 * @param peer (Peer) Peer to connect to.
		 */
		public function OutgoingConnector(stratusConnection:NetConnection, peer:Peer) {
			this.stratusConnection = stratusConnection;
			this.peer = peer;
		}
		
		
		/**
		 * This is a callback from the peer that you requested a connection
		 * with when they accept your request.
		 * 
		 * @param peer (Peer) The peer that accepted your connection.
		 * @param channel (String) The unique name of the channel that we should communicate on.
		 */
		public function onConnectionAccepted(peer:Peer, channel:String):void {
			if(this.peer.id == peer.id) {
				dispatchEvent(new OutgoingConnectionEvent(OutgoingConnectionEvent.OUTGOING_CONNECTION_ACCEPTED, peer, channel));
				requestStream.close();
			}
		}
		
		/**
		 * This method initiates a request to another peer.
		 */
		public function requestConnection():void {
			if(requestStream == null) {
				requestStream = new NetStream(stratusConnection, peer.id);
				requestStream.client = this;
				requestStream.play("listener");
			}
		}
		
	}
	
}